<?php
class Online_Ebay_Listing extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
				# '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'online_ebay_listing',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *        array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	
	static function getStoreCategories($shop_id, $site_id)
	{
		$result = Online_Ebay_Listing_API_Cache::getData(Q::ini('custom_flag/online_ebay_listing_api_cache_type/store_categories'), array('shop_id' => $shop_id, 'site_id' => $site_id));
		if ($result['ack'] == SUCCESS)
		{
			$response = json_decode(json_encode(simplexml_load_string($result['data'])));
			if (is_array($response->Store->CustomCategories->CustomCategory))
			{
				$api_categories = $response->Store->CustomCategories->CustomCategory;
			}
			else
			{
				$api_categories = array($response->Store->CustomCategories->CustomCategory);
			}
			$categories = Helper_BSS_Array::EbayStoreCategoriesArray($api_categories);
			return array('ack' => SUCCESS, 'message' => '', 'categories' => $categories);
		}
		$token = Shop_API_Ebay::find('shop_id=?', $shop_id)->asArray()->getOne();
		if ($token)
		{
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:GetStore'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<GetStoreRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<CategoryStructureOnly>true</CategoryStructureOnly>';
			$xml .= '</GetStoreRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GetStore');
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if ($response->Ack == 'Success')
				{
					Online_Ebay_Listing_API_Cache::updateFilename(Q::ini('custom_flag/online_ebay_listing_api_cache_type/store_categories'), $result['filename'], array('shop_id' => $shop_id, 'site_id' => $site_id));
					if (is_array($response->Store->CustomCategories->CustomCategory))
					{
						$api_categories = $response->Store->CustomCategories->CustomCategory;
					}
					else
					{
						$api_categories = array($response->Store->CustomCategories->CustomCategory);
					}
					$categories = Helper_BSS_Array::EbayStoreCategoriesArray($api_categories);
					return array('ack' => SUCCESS, 'message' => '', 'categories' => $categories);
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function getEbyDetails($site_id)
	{
		$result = Online_Ebay_Listing_API_Cache::getData(Q::ini('custom_flag/online_ebay_listing_api_cache_type/ebay_details'), array('site_id' => $site_id));
		if ($result['ack'] == SUCCESS)
		{
			$response = json_decode(json_encode(simplexml_load_string($result['data'])));
			$details = Helper_BSS_Array::EbayDetailArray($response);
			return array('ack' => SUCCESS, 'message' => '', 'details' => $details);
		}
		$token = Shop_API_Ebay::find()->asArray()->getOne();
		$header = array(
			'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
			'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
			'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
			'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
			'X-EBAY-API-SITEID:' . $site_id,
			'X-EBAY-API-CALL-NAME:GeteBayDetails'
		);
		$xml = '<?xml version="1.0" encoding="utf-8"?>';
		$xml .= '<GeteBayDetailsRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
		$xml .= 	'<RequesterCredentials>';
		$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
		$xml .= 	'</RequesterCredentials>';
		$xml .= 	'<DetailName>DispatchTimeMaxDetails</DetailName>';
		$xml .= 	'<DetailName>ShippingServiceDetails</DetailName>';
		$xml .= 	'<DetailName>ShippingLocationDetails</DetailName>';
		$xml .= 	'<DetailName>ReturnPolicyDetails</DetailName>';
		$xml .= 	'<WarningLevel>High</WarningLevel>';
		$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
		$xml .= '</GeteBayDetailsRequest>';
		$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GeteBayDetails');
		if ($result['ack'] == SUCCESS)
		{
			$response = json_decode(json_encode(simplexml_load_string($result['data'])));
			if ($response->Ack == 'Success')
			{
				Online_Ebay_Listing_API_Cache::updateFilename(Q::ini('custom_flag/online_ebay_listing_api_cache_type/ebay_details'), $result['filename'], array('site_id' => $site_id));
				$details = Helper_BSS_Array::EbayDetailArray($response);
				return array('ack' => SUCCESS, 'message' => '', 'details' => $details);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $result['message']);
		}
	}
	
	static function getCategoryFeatures($shop_id, $site_id, $category_id)
	{
		$result = Online_Ebay_Listing_API_Cache::getData(Q::ini('custom_flag/online_ebay_listing_api_cache_type/category_features'), array('site_id' => $site_id, 'category_id' => $category_id));
		if ($result['ack'] == SUCCESS)
		{
			$response = json_decode(json_encode(simplexml_load_string($result['data'])));
			$features = Helper_BSS_Array::EbayCategoryFeaturesArray($response->Category);
			return array('ack' => SUCCESS, 'message' => '', 'features' => $features);
		}
		$token = Shop_API_Ebay::find('shop_id=?', $shop_id)->asArray()->getOne();
		if ($token)
		{
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:GetCategoryFeatures'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<GetCategoryFeaturesRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<CategoryID>' . $category_id . '</CategoryID>';
			$xml .= 	'<DetailLevel>ReturnAll</DetailLevel>';
			$xml .=		'<OutputSelector>Category.VariationsEnabled</OutputSelector>';
			$xml .= 	'<OutputSelector>Category.CategoryID</OutputSelector>';
			$xml .= 	'<OutputSelector>Category.ConditionValues.Condition</OutputSelector>';
			$xml .= 	'<WarningLevel>High</WarningLevel>';
			$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
			$xml .= '</GetCategoryFeaturesRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GetCategoryFeatures');
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if ($response->Ack == 'Success')
				{
					Online_Ebay_Listing_API_Cache::updateFilename(Q::ini('custom_flag/online_ebay_listing_api_cache_type/category_features'), $result['filename'], array('site_id' => $site_id, 'category_id' => $category_id));
					$features = Helper_BSS_Array::EbayCategoryFeaturesArray($response->Category);
					return array('ack' => SUCCESS, 'message' => '', 'features' => $features);
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function getCategorySpecifics($shop_id, $site_id, $category_id)
	{
		$result = Online_Ebay_Listing_API_Cache::getData(Q::ini('custom_flag/online_ebay_listing_api_cache_type/category_specifics'), array('site_id' => $site_id, 'category_id' => $category_id));
		if ($result['ack'] == SUCCESS)
		{
			$response = json_decode(json_encode(simplexml_load_string($result['data'])));
			$specifics = Helper_BSS_Array::EbayCategorySpecificsArray($response->Recommendations);
			return array('ack' => SUCCESS, 'message' => '', 'specifics' => $specifics);
		}
		$token = Shop_API_Ebay::find('shop_id=?', $shop_id)->asArray()->getOne();
		if ($token)
		{
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:GetCategorySpecifics'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<GetCategorySpecificsRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<CategorySpecific>';
			$xml .= 		'<CategoryID>' . $category_id . '</CategoryID>';
			$xml .= 	'</CategorySpecific>';
			$xml .= 	'<DetailLevel>ReturnAll</DetailLevel>';
			$xml .= 	'<WarningLevel>High</WarningLevel>';
			$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
			$xml .= '</GetCategorySpecificsRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GetCategorySpecifics');
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if ($response->Ack == 'Success')
				{
					Online_Ebay_Listing_API_Cache::updateFilename(Q::ini('custom_flag/online_ebay_listing_api_cache_type/category_specifics'), $result['filename'], array('site_id' => $site_id, 'category_id' => $category_id));
					$specifics = Helper_BSS_Array::EbayCategorySpecificsArray($response->Recommendations);
					return array('ack' => SUCCESS, 'message' => '', 'specifics' => $specifics);
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function assembleListingByPost($post)
	{
		$listing = array();
		if (isset($post['id']))
		{
			$listing['id'] = $post['id'];
		}
		if (isset($post['folder_id']))
		{
			$listing['folder_id'] = $post['folder_id'];
		}
		else
		{
			$listing['folder_id'] = '';
		}
		if (isset($post['shop_id']))
		{
			$listing['shop_id'] = $post['shop_id'];
			$shop = Shop::find('id=?', $listing['shop_id'])->asArray()->getOne();
			$listing['payment_method'] = 'PayPal';
			$listing['payment_address'] = $shop['payment_address'];
		}
		if (isset($post['site']))
		{
			$listing['site'] = $post['site'];
			$listing['currency_id'] = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $post['site'], 'currency_id');
		}
		$listing['primary_category'] = $post['primary_category'];
		$listing['primary_category_name'] = $post['primary_category_name'];
		$listing['second_category'] = $post['second_category'];
		$listing['second_category_name'] = $post['second_category_name'];
		$listing['store_category'] = $post['store_category'];
		$listing['store_category2'] = $post['store_category2'];
		$listing['title'] = $post['title'];
		$listing['condition_id'] = $post['condition_id'];
		$listing['condition_name'] = $post['condition_name'];
		$listing['condition_description'] = $post['condition_description'];
		$listing['start_price'] = 0;
		$listing['quantity'] = 0;
		$listing_picture = $variation_picture = array();
		$picture_sort = 0;
		if (trim($post['picture_urls']))
		{
			$picture_urls = explode("\n", trim($post['picture_urls']));
			foreach ($picture_urls as $apu)
			{
				$listing_picture[] = array(
					'specific_name' => '',
					'specific_value' => '',
					'picture_url' => trim($apu),
					'sort' => $picture_sort++
				);
			}
		}
		$item = array();
		if ($post['listing_type'] == 'Chinese')
		{
			$listing['listing_type'] = 'Chinese';
			$listing['variation'] = Q::ini('custom_flag/online_ebay_listing_variation/not_variation/value');
			$listing['listing_duration'] = $post['Chinese_duration'];
			$one_item = array('sku' => $post['listing_sku'], 'quantity' => 1, 'start_price' => $post['Chinese_start_price'], 'buy_it_now_price' => $post['Chinese_buy_it_now_price']);
			$item[] = $one_item;
			$listing['quantity'] = 1;
			$listing['start_price'] = $post['Chinese_start_price'];
		}
		if ($post['listing_type'] == 'FixedPriceItem')
		{
			$listing['listing_type'] = 'FixedPriceItem';
			$listing['variation'] = Q::ini('custom_flag/online_ebay_listing_variation/not_variation/value');
			$listing['listing_duration'] = $post['FixedPriceItem_duration'];
			$one_item = array('sku' => $post['listing_sku'], 'quantity' => $post['FixedPriceItem_quantity'], 'start_price' => $post['FixedPriceItem_start_price']);
			$item[] = $one_item;
			$listing['quantity'] = $post['FixedPriceItem_quantity'];
			$listing['start_price'] = $post['FixedPriceItem_start_price'];
		}
		if ($post['listing_type'] == 'MultiSKU')
		{
			$listing['listing_type'] = 'FixedPriceItem';
			$listing['variation'] = Q::ini('custom_flag/online_ebay_listing_variation/variation/value');
			$listing['listing_duration'] = $post['MultiSKU_duration'];
			foreach ($post['variation'] as $pv)
			{
				$one_item = array();
				$one_item['sku'] = $pv['Sub SKU'];
				$one_item['quantity'] = $pv['Quantity'];
				$one_item['start_price'] = $pv['Price'];
				foreach ($pv['specifics'] as $key => $pvs)
				{
					$one_item['specifics'][] = array('name' => $key, 'value' => $pvs);
				}
				$item[] = $one_item;
				$listing['quantity'] += $pv['Quantity'];
				$listing['start_price'] = ($listing['start_price'] > 0) ? min($pv['Price'], $listing['start_price']) : $pv['Price'];
			}
			if (isset($post['MultiSKU_variation_pictures_specifics']) && $post['MultiSKU_variation_pictures_specifics'] && isset($post['variation_picture']) && $post['variation_picture'])
			{
				foreach ($post['variation_picture'] as $key => $pvp)
				{
					if ($pvp['url'])
					{
						$variation_picture[] = array(
							'specific_name' => $post['MultiSKU_variation_pictures_specifics'],
							'specific_value' => $key,
							'picture_url' => trim($pvp['url']),
							'sort' => $picture_sort++
						);
					}
				}
			}
		}
		$item_specifics = array();
		foreach ($post['item_specifics'] as $key => $is)
		{
			if (isset($is['checked']) && $is['value'])
			{
				$item_specifics[] = array('name' => $key, 'value' => $is['value']);
			}
		}
		if (isset($post['custom_item_specifics']))
		{
			foreach ($post['custom_item_specifics'] as $cis)
			{
				$item_specifics[] = array('name' => $cis['name'], 'value' => $cis['value']);
			}
		}
		$listing['description'] = $post['description'];
		$listing['counter'] = $post['counter'];
		$listing['auto_pay'] = isset($post['auto_pay']) ? Q::ini('custom_flag/online_ebay_listing_auto_pay/auto/value') : Q::ini('custom_flag/online_ebay_listing_auto_pay/not_auto/value');
		$listing['dispatch_time'] = $post['dispatch_time'];
		$listing['get_it_fast'] = isset($post['get_it_fast']) ? Q::ini('custom_flag/online_ebay_listing_get_it_fast/fast/value') : Q::ini('custom_flag/online_ebay_listing_get_it_fast/not_fast/value');
		$listing['country'] = $post['country'];
		$listing['postal_code'] = $post['postal_code'];
		$listing['location'] = $post['location'];
		$listing['return_policy'] = $post['return_policy'];
		$listing['return_option_restocking'] = isset($post['return_option_restocking']) ? $post['return_option_restocking'] : '';
		$listing['return_option_within'] = isset($post['return_option_within']) ? $post['return_option_within'] : '';
		$listing['return_option_refund'] = isset($post['return_option_refund']) ? $post['return_option_refund'] : '';
		$listing['return_option_paid_by'] = isset($post['return_option_paid_by']) ? $post['return_option_paid_by'] : '';
		$listing['return_option_description'] = isset($post['return_option_description']) ? $post['return_option_description'] : '';
		$shipping_sort = 0;
		$domestic_shipping = array();
		foreach ($post['domestic_shipping'] as $ds)
		{
			$domestic_shipping[] = array(
				'service' => $ds['service'],
				'cost' => isset($ds['cost']) ? $ds['cost'] : 0,
				'additional_cost' => isset($ds['additional_cost']) ? $ds['additional_cost'] : 0,
				'free' => isset($ds['free']) ? Q::ini('custom_flag/online_ebay_listing_shipping_free/free/value') : Q::ini('custom_flag/online_ebay_listing_shipping_free/not_free/value'),
				'sort' => $shipping_sort++
			);
		}
		$international_shipping = array();
		if (isset($post['international_shipping']))
		{
			foreach ($post['international_shipping'] as $is)
			{
				if ($is['service'])
				{
					$international_shipping[] = array(
						'service' => $is['service'],
						'cost' => isset($is['cost']) ? $is['cost'] : 0,
						'additional_cost' => isset($is['additional_cost']) ? $is['additional_cost'] : 0,
						'free' => isset($is['free']) ? Q::ini('custom_flag/online_ebay_listing_shipping_free/free/value') : Q::ini('custom_flag/online_ebay_listing_shipping_free/not_free/value'),
						'shipping_location' => ($is['location'] == 'Worldwide') ? 'Worldwide' : implode(',', $is['location_custom']),
						'sort' => $shipping_sort++
					);
				}
			}
		}
		$listing['item'] = $item;
		$listing['item_specifics'] = $item_specifics;
		$listing['picture'] = array('listing_picture' => $listing_picture, 'variation_picture' => $variation_picture);
		$listing['shipping_service'] = array('domestic_shipping' => $domestic_shipping, 'international_shipping' => $international_shipping);
		if (isset($post['set_schedule']) && isset($post['date']) && $post['date'])
		{
			$listing['schedule_flag'] = Q::ini('custom_flag/online_ebay_listing_schedule_flag/set/value');
			$listing['schedule_time_show_timezone'] = $post['timezone'];
			$listing['schedule_time'] = $post['date'] . ' ' . $post['hour'] . ':' . $post['minute'] . ':00';
			if (isset($post['schedule_repeat']) && isset($post['schedule_repeat_step']) && trim($post['schedule_repeat_step']) >= 1)
			{
				$listing['schedule_repeat'] = Q::ini('custom_flag/online_ebay_listing_schedule_repeat/repeat/value');
				$listing['schedule_repeat_step'] = $post['schedule_repeat_step'];
			}
			else
			{
				$listing['schedule_repeat'] = Q::ini('custom_flag/online_ebay_listing_schedule_repeat/no_repeat/value');
				$listing['schedule_repeat_step'] = '';
			}
		}
		else
		{
			$listing['schedule_flag'] = Q::ini('custom_flag/online_ebay_listing_schedule_flag/not_set/value');
			$listing['schedule_time_show_timezone'] = '';
			$listing['schedule_time'] = '';
			$listing['schedule_repeat'] = Q::ini('custom_flag/online_ebay_listing_schedule_repeat/no_repeat/value');
			$listing['schedule_repeat_step'] = '';
		}
		return $listing;
	}
	
	static function create($listing)
	{
		$create = new Online_Ebay_Listing();
		$create->online_ebay_listing_folder_id = $listing['folder_id'];
		$create->shop_id = $listing['shop_id'];
		$create->site = $listing['site'];
		$create->currency_id = $listing['currency_id'];
		$create->primary_category = $listing['primary_category'];
		$create->second_category = $listing['second_category'];
		$create->store_category = $listing['store_category'] ? $listing['store_category'] : 0;
		$create->store_category2 = $listing['store_category2'] ? $listing['store_category2'] : 0;
		$create->condition_id = $listing['condition_id'];
		$create->condition_name = $listing['condition_name'];
		$create->condition_description = $listing['condition_description'];
		$create->listing_type = $listing['listing_type'];
		$create->variation = $listing['variation'];
		$create->listing_duration = $listing['listing_duration'];
		$create->start_price = $listing['start_price'];
		$create->quantity = $listing['quantity'];
		$create->counter = $listing['counter'];
		$create->payment_method = $listing['payment_method'];
		$create->payment_address = $listing['payment_address'];
		$create->auto_pay = $listing['auto_pay'];
		$create->dispatch_time = $listing['dispatch_time'];
		$create->get_it_fast = $listing['get_it_fast'];
		$create->country = $listing['country'];
		$create->postal_code = $listing['postal_code'];
		$create->location = $listing['location'];
		$create->sell_status = 0;
		$create->schedule_flag = $listing['schedule_flag'];
		$create->schedule_next_time = $listing['schedule_time'];
		$create->schedule_time_show_timezone = $listing['schedule_time_show_timezone'];
		$create->schedule_repeat = $listing['schedule_repeat'];
		$create->schedule_repeat_step = $listing['schedule_repeat_step'];
		$create->create_user_id = CURRENT_USER_ID;
		$create->create_time = CURRENT_DATETIME;
		$create->lib_flag = Q::ini('custom_flag/ebay_listing_lib_flag/flag/value');
		$create->save();
		$extend = array();
		$extend['title'] = $listing['title'];
		$extend['description'] = $listing['description'];
		$extend['return_policy'] = $listing['return_policy'];
		$extend['return_option_restocking'] = $listing['return_option_restocking'];
		$extend['return_option_within'] = $listing['return_option_within'];
		$extend['return_option_refund'] = $listing['return_option_refund'];
		$extend['return_option_paid_by'] = $listing['return_option_paid_by'];
		$extend['return_option_description'] = $listing['return_option_description'];
		$listing_id = $create['id'];
		Online_Ebay_Listing_Extend::update($extend, $listing_id);
		Online_Ebay_Listing_Item::create($listing['item'], $listing_id);
		Online_Ebay_Listing_Specifics::create($listing['item_specifics'], $listing_id, Q::ini('custom_flag/online_ebay_listing_specifics_type/listing'));
		Online_Ebay_Listing_Picture::create($listing['picture']['listing_picture'], $listing_id, Q::ini('custom_flag/online_ebay_listing_picture_type/listing/value'));
		Online_Ebay_Listing_Picture::create($listing['picture']['variation_picture'], $listing_id, Q::ini('custom_flag/online_ebay_listing_picture_type/variation/value'));
		Online_Ebay_Listing_Picture::makeEPS($listing_id);
		Online_Ebay_Listing_Shipping::create($listing['shipping_service']['domestic_shipping'], $listing_id, Q::ini('custom_flag/online_ebay_listing_shipping_type/domestic/value'));
		Online_Ebay_Listing_Shipping::create($listing['shipping_service']['international_shipping'], $listing_id, Q::ini('custom_flag/online_ebay_listing_shipping_type/international/value'));
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function edit($listing)
	{
		$edit = Online_Ebay_Listing::find('id=?', $listing['id'])->getOne();
		if ( ! $edit['id'])
		{
			return array('ack' => FAILURE, 'message' => 'listing不存在');
		}
		$edit->online_ebay_listing_folder_id = $listing['folder_id'];
		$edit->primary_category = $listing['primary_category'];
		$edit->second_category = $listing['second_category'];
		$edit->store_category = $listing['store_category'] ? $listing['store_category'] : 0;
		$edit->store_category2 = $listing['store_category2'] ? $listing['store_category2'] : 0;
		$edit->condition_id = $listing['condition_id'];
		$edit->condition_name = $listing['condition_name'];
		$edit->condition_description = $listing['condition_description'];
		$edit->listing_type = $listing['listing_type'];
		$edit->variation = $listing['variation'];
		$edit->listing_duration = $listing['listing_duration'];
		$edit->start_price = $listing['start_price'];
		$edit->quantity = $listing['quantity'];
		$edit->counter = $listing['counter'];
		$edit->auto_pay = $listing['auto_pay'];
		$edit->dispatch_time = $listing['dispatch_time'];
		$edit->get_it_fast = $listing['get_it_fast'];
		$edit->country = $listing['country'];
		$edit->postal_code = $listing['postal_code'];
		$edit->location = $listing['location'];
		if ( ! $edit['item_id'])
		{
			$edit->schedule_flag = $listing['schedule_flag'];
			$edit->schedule_next_time = $listing['schedule_time'];
			$edit->schedule_time_show_timezone = $listing['schedule_time_show_timezone'];
			$edit->schedule_repeat = $listing['schedule_repeat'];
			$edit->schedule_repeat_step = $listing['schedule_repeat_step'];
		}
		$edit->save();
		$extend = array();
		$extend['title'] = $listing['title'];
		$extend['description'] = $listing['description'];
		$extend['return_policy'] = $listing['return_policy'];
		$extend['return_option_restocking'] = $listing['return_option_restocking'];
		$extend['return_option_within'] = $listing['return_option_within'];
		$extend['return_option_refund'] = $listing['return_option_refund'];
		$extend['return_option_paid_by'] = $listing['return_option_paid_by'];
		$extend['return_option_description'] = $listing['return_option_description'];
		Online_Ebay_Listing_Extend::update($extend, $listing['id']);
		Online_Ebay_Listing_Item::update($listing['item'], $listing['id']);
		Online_Ebay_Listing_Specifics::update($listing['item_specifics'], $listing['id'], Q::ini('custom_flag/online_ebay_listing_specifics_type/listing'));
		Online_Ebay_Listing_Picture::update($listing['picture']['listing_picture'], $listing['id'], Q::ini('custom_flag/online_ebay_listing_picture_type/listing/value'));
		Online_Ebay_Listing_Picture::update($listing['picture']['variation_picture'], $listing['id'], Q::ini('custom_flag/online_ebay_listing_picture_type/variation/value'));
		Online_Ebay_Listing_Picture::makeEPS($listing['id']);
		Online_Ebay_Listing_Shipping::update($listing['shipping_service']['domestic_shipping'], $listing['id'], Q::ini('custom_flag/online_ebay_listing_shipping_type/domestic/value'));
		Online_Ebay_Listing_Shipping::update($listing['shipping_service']['international_shipping'], $listing['id'], Q::ini('custom_flag/online_ebay_listing_shipping_type/international/value'));
		if ($edit['lib_flag'] == Q::ini('custom_flag/ebay_listing_lib_flag/unflag/value'))
		{
			$push_result = Online_Ebay_Listing::pushRevise($listing['id']);
			if ($push_result['ack'] != SUCCESS)
			{
				return array('ack' => FAILURE, 'message' => $push_result['message']);
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function copy($listing, $listing_id)
	{
		$listing_in_db = Online_Ebay_Listing::find('id=?', $listing_id)->asArray()->getOne();
		$create_listing = new Online_Ebay_Listing();
		$create_listing->online_ebay_listing_folder_id = $listing['folder_id'];
		$create_listing->shop_id = $listing['shop_id'];
		$create_listing->site = $listing_in_db['site'];
		$create_listing->currency_id = $listing_in_db['currency_id'];
		$create_listing->primary_category = $listing_in_db['primary_category'];
		$create_listing->second_category = $listing_in_db['second_category'];
		$create_listing->store_category = $listing_in_db['store_category'] ? $listing_in_db['store_category'] : 0;
		$create_listing->store_category2 = $listing_in_db['store_category2'] ? $listing_in_db['store_category2'] : 0;
		$create_listing->condition_id = $listing_in_db['condition_id'];
		$create_listing->condition_name = $listing_in_db['condition_name'];
		$create_listing->condition_description = $listing_in_db['condition_description'];
		$create_listing->listing_type = $listing_in_db['listing_type'];
		$create_listing->variation = $listing_in_db['variation'];
		$create_listing->listing_duration = $listing_in_db['listing_duration'];
		$create_listing->start_price = $listing_in_db['start_price'];
		$create_listing->quantity = $listing_in_db['quantity'];
		$create_listing->counter = $listing_in_db['counter'];
		$create_listing->payment_method = $listing_in_db['payment_method'];
		$create_listing->payment_address = $listing_in_db['payment_address'];
		$create_listing->auto_pay = $listing_in_db['auto_pay'];
		$create_listing->dispatch_time = $listing_in_db['dispatch_time'];
		$create_listing->get_it_fast = $listing_in_db['get_it_fast'];
		$create_listing->country = $listing_in_db['country'];
		$create_listing->postal_code = $listing_in_db['postal_code'];
		$create_listing->location = $listing_in_db['location'];
		$create_listing->sell_status = 0;
		$create_listing->create_user_id = CURRENT_USER_ID;
		$create_listing->create_time = CURRENT_DATETIME;
		$create_listing->lib_flag = Q::ini('custom_flag/ebay_listing_lib_flag/flag/value');
		$create_listing->save();
		
		$extend_in_db = Online_Ebay_Listing_Extend::find('online_ebay_listing_id=?', $listing_id)->asArray()->getOne();
		$extend_in_db['title'] = $listing['title'];
		$extend_in_db['view_url'] = '';
		if (isset($listing['template_id']) && $listing['template_id'])
		{
			$template = Ebay_Template::getTemplatePreview($listing['template_id'], 'outsite');
			$extend_in_db['description'] = str_replace(array('{{{desc_text}}}', '{{{desc_img}}}'), array($listing['desc_text'], $listing['desc_img']), $template['response']);
		}
		else
		{
			$extend_in_db['description'] = '';
		}
		Online_Ebay_Listing_Extend::update($extend_in_db, $create_listing['id']);
		
		$item_in_db = Online_Ebay_Listing_Item::find('online_ebay_listing_id=?', $listing_id)->asArray()->getAll();
		foreach ($item_in_db as $i)
		{
			$listing_item = new Online_Ebay_Listing_Item();
			$listing_item->online_ebay_listing_id = $create_listing['id'];
			$listing_item->product_basic_id = $i['product_basic_id'];
			$listing_item->sku = $i['sku'];
			$listing_item->quantity = $i['quantity'];
			$listing_item->start_price = $i['start_price'];
			$listing_item->buy_it_now_price = $i['buy_it_now_price'];
			$listing_item->sold_quantity = $i['sold_quantity'];
			$listing_item->save();
			$item_id = $listing_item['id'];
			$Specifics = Online_Ebay_Listing_Specifics::find('relate_table_id=?', $i['id'])->asArray()->getAll();
			if ($Specifics)
			{
				Online_Ebay_Listing_Specifics::create($Specifics, $item_id, Q::ini('custom_flag/online_ebay_listing_specifics_type/variation'));
			}
		}
		
		$specifics_in_db = Online_Ebay_Listing_Specifics::find('relate_table_id=? and type=?', $listing_id, Q::ini('custom_flag/online_ebay_listing_specifics_type/listing'))->asArray()->getAll();
		Online_Ebay_Listing_Specifics::create($specifics_in_db, $create_listing['id'], Q::ini('custom_flag/online_ebay_listing_specifics_type/listing'));
		
		$picture_in_db = Online_Ebay_Listing_Picture::find('online_ebay_listing_id=?', $listing_id)->asArray()->getAll();
		foreach ($picture_in_db as $p)
		{
			$create_picture = new Online_Ebay_Listing_Picture();
			$create_picture->online_ebay_listing_id = $create_listing['id'];
			$create_picture->type = $p['type'];
			$create_picture->specific_name = $p['specific_name'];
			$create_picture->specific_value = $p['specific_value'];
			$create_picture->picture_url = $p['picture_url'];
			$create_picture->sort = $p['sort'];
			$create_picture->save();
		}
		Online_Ebay_Listing_Picture::makeEPS($create_listing['id']);
		
		$shipping_in_db = Online_Ebay_Listing_Shipping::find('online_ebay_listing_id=?', $listing_id)->asArray()->getAll();
		foreach ($shipping_in_db as $s)
		{
			$shipping_service = new Online_Ebay_Listing_Shipping();
			$shipping_service->online_ebay_listing_id = $create_listing['id'];
			$shipping_service->type = $s['type'];
			$shipping_service->service = $s['service'];
			$shipping_service->cost = $s['cost'];
			$shipping_service->additional_cost = $s['additional_cost'];
			$shipping_service->free = $s['free'];
			$shipping_service->sort = $s['sort'];
			if (isset($s['shipping_location']))
			{
				$shipping_service->shipping_location = $s['shipping_location'];
			}
			$shipping_service->save();
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function delete($listing_id)
	{
		Online_Ebay_Listing_Item::delete($listing_id);
		Online_Ebay_Listing_Specifics::delete($listing_id, Q::ini('custom_flag/online_ebay_listing_specifics_type/listing'));
		Online_Ebay_Listing_Picture::delete($listing_id);
		Online_Ebay_Listing_Shipping::delete($listing_id);
		Online_Ebay_Listing_Extend::delete($listing_id);
		Online_Ebay_Listing::meta()->deleteWhere('id=?', $listing_id);
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function update($listing)
	{
		if (isset($listing['id']))
		{
			$update = Online_Ebay_Listing::find('id=?', $listing['id'])->getOne();
			if ( ! $update['id'])
			{
				return array('ack' => FAILURE, 'message' => 'listing不存在');
			}
		}
		else
		{
			//for relist
			$shop = Shop::find('id=?', $listing['shop_id'])->asArray()->getOne();
			$update = new Online_Ebay_Listing();
			$update->site = $listing['site'];
			$update->shop_id = $listing['shop_id'];
			$update->item_id = $listing['item_id'];
			$update->currency_id = $listing['currency_id'];
			$update->payment_method = 'PayPal';
			$update->payment_address = $shop['payment_address'];
		}
		$update->primary_category = $listing['primary_category'];
		$update->second_category = $listing['second_category'];
		$update->store_category = $listing['store_category'] ? $listing['store_category'] : 0;
		$update->store_category2 = $listing['store_category2'] ? $listing['store_category2'] : 0;
		$update->condition_id = $listing['condition_id'];
		$update->condition_name = $listing['condition_name'];
		$update->condition_description = $listing['condition_description'];
		$update->listing_type = $listing['listing_type'];
		$update->variation = $listing['variation'];
		$update->listing_duration = $listing['listing_duration'];
		$update->start_price = $listing['start_price'];
		$update->quantity = $listing['quantity'];
		$update->sold_quantity = $listing['sold_quantity'];
		$update->watch_count = $listing['watch_count'];
		$update->hit_count = $listing['hit_count'];
		$update->counter = $listing['counter'];
		$update->auto_pay = $listing['auto_pay'];
		$update->dispatch_time = $listing['dispatch_time'];
		$update->get_it_fast = $listing['get_it_fast'];
		$update->country = $listing['country'];
		$update->postal_code = $listing['postal_code'];
		$update->location = $listing['location'];
		$update->start_time = $listing['start_time'];
		$update->end_time = $listing['end_time'];
		$update->sell_status = $listing['sell_status'];
		$update->update_time = CURRENT_DATETIME;
		$update->save();
		$listing_id = $update['id'];
		$extend = array();
		$extend['title'] = $listing['title'];
		$extend['description'] = $listing['description'];
		$extend['view_url'] = $listing['view_url'];
		$extend['return_policy'] = $listing['return_policy'];
		$extend['return_option_restocking'] = $listing['return_option_restocking'];
		$extend['return_option_within'] = $listing['return_option_within'];
		$extend['return_option_refund'] = $listing['return_option_refund'];
		$extend['return_option_paid_by'] = $listing['return_option_paid_by'];
		$extend['return_option_description'] = $listing['return_option_description'];
		Online_Ebay_Listing_Extend::update($extend, $listing_id);
 		Online_Ebay_Listing_Item::update($listing['item'], $listing_id);
		Online_Ebay_Listing_Specifics::update($listing['item_specifics'], $listing_id, Q::ini('custom_flag/online_ebay_listing_specifics_type/listing'));
		Online_Ebay_Listing_Picture::update($listing['picture']['listing_picture'], $listing_id, Q::ini('custom_flag/online_ebay_listing_picture_type/listing/value'));
		Online_Ebay_Listing_Picture::update($listing['picture']['variation_picture'], $listing_id, Q::ini('custom_flag/online_ebay_listing_picture_type/variation/value'));
		Online_Ebay_Listing_Shipping::update($listing['shipping_service']['domestic_shipping'], $listing_id, Q::ini('custom_flag/online_ebay_listing_shipping_type/domestic/value'));
		Online_Ebay_Listing_Shipping::update($listing['shipping_service']['international_shipping'], $listing_id, Q::ini('custom_flag/online_ebay_listing_shipping_type/international/value'));
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function pushRevise($listing_id)
	{
		$get_result = Online_Ebay_Listing::getListingById($listing_id);
		if ($get_result['ack'] == SUCCESS)
		{
			if ($get_result['listing']['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
			{
				$revise_result = Online_Ebay_Listing::reviseFixedPriceItem($get_result['listing']);
				if ($revise_result['ack'] != SUCCESS)
				{
					return array('ack' => FAILURE, 'message' => $revise_result['message']);
				}
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				$revise_result = Online_Ebay_Listing::reviseItem($get_result['listing']);
				if ($revise_result['ack'] != SUCCESS)
				{
					return array('ack' => FAILURE, 'message' => $revise_result['message']);
				}
				return array('ack' => SUCCESS, 'message' => '');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $get_result['message']);
		}
	}
	
	static function pushAdd($listing_id, $type)
	{
		$get_result = Online_Ebay_Listing::getListingById($listing_id);
		if ($get_result['ack'] == SUCCESS)
		{
			if ($get_result['listing']['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
			{
				$add_result = Online_Ebay_Listing::addFixedPriceItem($get_result['listing'], $type);
			}
			else
			{
				$add_result = Online_Ebay_Listing::addItem($get_result['listing'], $type);
			}
			//标记push_flag
			if ($add_result['ack'] == SUCCESS)
			{
				$listing = Online_Ebay_Listing::find('id=?', $listing_id)->getOne();
				$listing->push_flag = Q::ini('custom_flag/ebay_listing_push_flag/flag/value');
				$listing->save();
			}
			//生成log
			$log = array(
			    'listing_id' => $listing_id,
				'item_id' => isset($add_result['item_id']) ? $add_result['item_id'] : '',
				'type' => $type,
				'user_id' => CURRENT_USER_ID,
				'time' => CURRENT_DATETIME,
				'ack' => isset($add_result['ack']) ? $add_result['ack'] : SUCCESS,
				'message' => isset($add_result['message']) ? $add_result['message'] : ''
			);
			Online_Ebay_Listing_Log::create($log);
			return array('ack' => $log['ack'], 'message' => $log['message']);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $get_result['message']);
		}
	}
	
	static function verifyAddItem($listing)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $listing['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
			$currency = Currency::find('id=?', $listing['currency_id'])->asArray()->getOne();
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:VerifyAddItem'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<VerifyAddItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<WarningLevel>High</WarningLevel>';
			$xml .= 	'<Item>';
			$xml .= 		'<Site>' . $listing['site'] . '</Site>';
			$xml .=			'<Currency>' . $currency['code'] . '</Currency>';
			$xml .= Online_Ebay_Listing::assembleItemXMLByListing($listing);
			$xml .= 	'</Item>';
			$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
			$xml .= '</VerifyAddItemRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'VerifyAddItem');
			if ($result['ack'] == SUCCESS)
			{
				$response = simplexml_load_string($result['data']);
				$verify_result = array('ack' => (string)$response->Ack[0], 'errors' => array(), 'fee' => '');
				if (isset($response->Errors[0]))
				{
					foreach ($response->Errors as $e)
					{
						$verify_result['errors'][] = htmlspecialchars($e->LongMessage[0]);
					}
				}
				if (isset($response->Fees[0]->Fee[0]))
				{
					foreach ($response->Fees[0]->Fee as $f)
					{
						if ($f->Name[0] == 'ListingFee')
						{
							$verify_result['fee'] = $f->Fee[0] . $f->Fee[0]->attributes();
						}
					}
				}
				return array('ack' => SUCCESS, 'message' => '', 'verify_result' => $verify_result);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function verifyAddFixedPriceItem($listing)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $listing['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
			$currency = Currency::find('id=?', $listing['currency_id'])->asArray()->getOne();
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:VerifyAddFixedPriceItem'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<VerifyAddFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<WarningLevel>High</WarningLevel>';
			$xml .= 	'<Item>';
			$xml .= 		'<Site>' . $listing['site'] . '</Site>';
			$xml .=			'<Currency>' . $currency['code'] . '</Currency>';
			$xml .= Online_Ebay_Listing::assembleItemXMLByListing($listing);
			$xml .= 	'</Item>';
			$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
			$xml .= '</VerifyAddFixedPriceItemRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'VerifyAddFixedPriceItem');
			if ($result['ack'] == SUCCESS)
			{
				$response = simplexml_load_string($result['data']);
				$verify_result = array('ack' => (string)$response->Ack[0], 'errors' => array(), 'fee' => '');
				if (isset($response->Errors[0]))
				{
					foreach ($response->Errors as $e)
					{
						$verify_result['errors'][] = htmlspecialchars($e->LongMessage[0]);
					}
				}
				if (isset($response->Fees[0]->Fee[0]))
				{
					foreach ($response->Fees[0]->Fee as $f)
					{
						if ($f->Name[0] == 'ListingFee')
						{
							$verify_result['fee'] = $f->Fee[0] . $f->Fee[0]->attributes();
						}
					}
				}
				return array('ack' => SUCCESS, 'message' => '', 'verify_result' => $verify_result);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function addItem($listing)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $listing['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
			$currency = Currency::find('id=?', $listing['currency_id'])->asArray()->getOne();
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:AddItem'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<AddItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<WarningLevel>High</WarningLevel>';
			$xml .= 	'<Item>';
			$xml .= 		'<Site>' . $listing['site'] . '</Site>';
			$xml .=			'<Currency>' . $currency['code'] . '</Currency>';
			$xml .= Online_Ebay_Listing::assembleItemXMLByListing($listing);
			$xml .= 	'</Item>';
			$xml .= '</AddItemRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'AddItem');
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if (strtolower($response->Ack) == 'success' || strtolower($response->Ack) == 'warning')
				{
					$listing_new = new Online_Ebay_Listing();
					$listing_new->shop_id = $listing['shop_id'];
					$listing_new->site = $listing['site'];
					$listing_new->item_id = $response->ItemID;
					$listing_new->lib_flag = Q::ini('custom_flag/ebay_listing_lib_flag/unflag/value');
					$listing_new->currency_id = $listing['currency_id'];
					$listing_new->payment_method = $listing['payment_method'];
					$listing_new->payment_address = $listing['payment_address'];
					$listing_new->save();
					$listing_new_id = mysql_insert_id();
					Online_Ebay_Listing::updateListing($listing_new_id, true);
					return array('ack' => SUCCESS, 'message' => '', 'item_id' => $response->ItemID);
				}
				else
				{
					$errors = array();
					if (isset($response->Errors))
					{
						if (is_array($response->Errors))
						{
							foreach ($response->Errors as $e)
							{
								$errors[] = htmlspecialchars($e->LongMessage);
							}
						}
						else
						{
							$errors[] = htmlspecialchars($response->Errors->LongMessage);
						}
					}
					return array('ack' => FAILURE, 'message' => implode('; ', $errors));
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function addFixedPriceItem($listing)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $listing['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
			$currency = Currency::find('id=?', $listing['currency_id'])->asArray()->getOne();
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:AddFixedPriceItem'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<AddFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<WarningLevel>High</WarningLevel>';
			$xml .= 	'<Item>';
			$xml .= 		'<Site>' . $listing['site'] . '</Site>';
			$xml .=			'<Currency>' . $currency['code'] . '</Currency>';
			$xml .= Online_Ebay_Listing::assembleItemXMLByListing($listing);
			$xml .= 	'</Item>';
			$xml .= '</AddFixedPriceItemRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'AddFixedPriceItem');
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if (strtolower($response->Ack) == 'success' || strtolower($response->Ack) == 'warning')
				{
					$listing_new = new Online_Ebay_Listing();
					$listing_new->shop_id = $listing['shop_id'];
					$listing_new->site = $listing['site'];
					$listing_new->item_id = $response->ItemID;
					$listing_new->currency_id = $listing['currency_id'];
					$listing_new->lib_flag = Q::ini('custom_flag/ebay_listing_lib_flag/unflag/value');
					$listing_new->payment_method = $listing['payment_method'];
					$listing_new->payment_address = $listing['payment_address'];
					$listing_new->save();
					$listing_new_id = mysql_insert_id();
					Online_Ebay_Listing::updateListing($listing_new_id, true);
					return array('ack' => SUCCESS, 'message' => '', 'item_id' => $response->ItemID);
				}
				else
				{
					$errors = array();
					if (isset($response->Errors))
					{
						if (is_array($response->Errors))
						{
							foreach ($response->Errors as $e)
							{
								$errors[] = htmlspecialchars($e->LongMessage);
							}
						}
						else
						{
							$errors[] = htmlspecialchars($response->Errors->LongMessage);
						}
					}
					return array('ack' => FAILURE, 'message' => implode('; ', $errors));
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function reviseItem($listing)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $listing['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:ReviseItem'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<ReviseItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<WarningLevel>High</WarningLevel>';
			$xml .= 	'<Item>';
			$xml .= 		'<ItemID>' . $listing['item_id'] . '</ItemID>';
			$xml .= Online_Ebay_Listing::assembleItemXMLByListing($listing);
			$xml .= 	'</Item>';
			$xml .= '</ReviseItemRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'ReviseItem');
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if (strtolower($response->Ack) == 'success' || strtolower($response->Ack) == 'warning')
				{
					Online_Ebay_Listing::updateListing($listing['id'], true);
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					$errors = array();
					if (isset($response->Errors))
					{
						if (is_array($response->Errors))
						{
							foreach ($response->Errors as $e)
							{
								$errors[] = htmlspecialchars($e->LongMessage);
							}
						}
						else
						{
							$errors[] = htmlspecialchars($response->Errors->LongMessage);
						}
					}
					return array('ack' => FAILURE, 'message' => implode('; ', $errors));
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function reviseFixedPriceItem($listing)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $listing['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:ReviseFixedPriceItem'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<ReviseFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<WarningLevel>High</WarningLevel>';
			$xml .= 	'<Item>';
			$xml .= 		'<ItemID>' . $listing['item_id'] . '</ItemID>';
			$xml .= Online_Ebay_Listing::assembleItemXMLByListing($listing);
			$xml .= 	'</Item>';
			$xml .= '</ReviseFixedPriceItemRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'ReviseFixedPriceItem');
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if (strtolower($response->Ack) == 'success' || strtolower($response->Ack) == 'warning')
				{
					Online_Ebay_Listing::updateListing($listing['id'], true);
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					$errors = array();
					if (isset($response->Errors))
					{
						if (is_array($response->Errors))
						{
							foreach ($response->Errors as $e)
							{
								$errors[] = htmlspecialchars($e->LongMessage);
							}
						}
						else
						{
							$errors[] = htmlspecialchars($response->Errors->LongMessage);
						}
					}
					return array('ack' => FAILURE, 'message' => implode('; ', $errors));
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function reviseInventoryAndPrice($listing)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $listing['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
			if ($listing['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
			{
				$header = array(
					'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
					'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
					'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
					'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
					'X-EBAY-API-SITEID:' . $site_id,
					'X-EBAY-API-CALL-NAME:ReviseFixedPriceItem'
				);
				$xml = '<?xml version="1.0" encoding="utf-8"?>';
				$xml .= '<ReviseFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
				$xml .= 	'<RequesterCredentials>';
				$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
				$xml .= 	'</RequesterCredentials>';
				$xml .= 	'<WarningLevel>High</WarningLevel>';
				$xml .= 	'<Item>';
				$xml .= 		'<ItemID>' . $listing['item_id'] . '</ItemID>';
				$xml .= 		'<OutOfStockControl>true</OutOfStockControl>';
				$xml .= 		'<Variations>';
				foreach ($listing['item'] as $li)
				{
					$xml .= 		'<Variation>';
					$xml .=				'<SKU>' . $li['sku'] . '</SKU>';
					$xml .= 			'<StartPrice>' . $li['start_price'] . '</StartPrice>';
					$xml .= 			'<Quantity>' . $li['quantity'] . '</Quantity>';
					$xml .= 		'</Variation>';
				}
				$xml .= 		'</Variations>';
				$xml .= 	'</Item>';
				$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
				$xml .= '</ReviseFixedPriceItemRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'ReviseFixedPriceItem');
			}
			else
			{
				$first_item = current($listing['item']);
				$header = array(
					'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
					'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
					'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
					'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
					'X-EBAY-API-SITEID:' . $site_id,
					'X-EBAY-API-CALL-NAME:ReviseItem'
				);
				$xml = '<?xml version="1.0" encoding="utf-8"?>';
				$xml .= '<ReviseItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
				$xml .= 	'<RequesterCredentials>';
				$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
				$xml .= 	'</RequesterCredentials>';
				$xml .= 	'<WarningLevel>High</WarningLevel>';
				$xml .= 	'<Item>';
				$xml .= 		'<ItemID>' . $listing['item_id'] . '</ItemID>';
				$xml .= 		'<OutOfStockControl>true</OutOfStockControl>';
				$xml .= 		'<SKU>' . $first_item['sku'] . '</SKU>';
				$xml .= 		'<StartPrice>' . $first_item['start_price'] . '</StartPrice>';
				$xml .= 		'<Quantity>' . $first_item['quantity'] . '</Quantity>';
				$xml .= 	'</Item>';
				$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
				$xml .= '</ReviseItemRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'ReviseItem');
			}
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if ($response->Ack == 'Success' || $response->Ack == 'Warning')
				{
					foreach ($listing['item'] as $li)
					{
						QDB::getConn()->execute('update online_ebay_listing_item set start_price=' . $li['start_price'] . ',quantity=' . $li['quantity'] . ' where online_ebay_listing_id=' . $listing['id'] . ' and sku=\'' . $li['sku'] . '\'');
					}
					Online_Ebay_Listing::updateListingPriceAndQuantity($listing['id']);
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					$errors = array();
					if (isset($response->Errors))
					{
						if (is_array($response->Errors))
						{
							foreach ($response->Errors as $e)
							{
								$errors[] = htmlspecialchars($e->LongMessage);
							}
						}
						else
						{
							$errors[] = htmlspecialchars($response->Errors->LongMessage);
						}
					}
					return array('ack' => FAILURE, 'message' => implode(', ', $errors));
				}
			}
			else
			{
				return array('ack' => SUCCESS, 'message' => $result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function relist($listing_id)
	{
		$listing = Online_Ebay_Listing::find('id=?', $listing_id)->asArray()->getOne();
		if ( ! $listing)
		{
			return array('ack' => FAILURE, 'message' => '该listing不存在');
		}
		$token = Shop_API_Ebay::find('shop_id=?', $listing['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
			if ($listing['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
			{
				$header = array(
					'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
					'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
					'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
					'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
					'X-EBAY-API-SITEID:' . $site_id,
					'X-EBAY-API-CALL-NAME:RelistFixedPriceItem'
				);
				$xml = '<?xml version="1.0" encoding="utf-8"?>';
				$xml .= '<RelistFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
				$xml .= 	'<RequesterCredentials>';
				$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
				$xml .= 	'</RequesterCredentials>';
				$xml .= 	'<Item>';
				$xml .= 		'<ItemID>' . $listing['item_id'] . '</ItemID>';
				$xml .= 	'</Item>';
				$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
				$xml .= '</RelistFixedPriceItemRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'RelistFixedPriceItem');
			}
			else
			{
				$header = array(
					'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
					'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
					'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
					'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
					'X-EBAY-API-SITEID:' . $site_id,
					'X-EBAY-API-CALL-NAME:RelistItem'
				);
				$xml = '<?xml version="1.0" encoding="utf-8"?>';
				$xml .= '<RelistItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
				$xml .= 	'<RequesterCredentials>';
				$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
				$xml .= 	'</RequesterCredentials>';
				$xml .= 	'<Item>';
				$xml .= 		'<ItemID>' . $listing['item_id'] . '</ItemID>';
				$xml .= 	'</Item>';
				$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
				$xml .= '</RelistItemRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'RelistItem');
			}
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if (isset($response->ItemID))
				{
					$item_id = $response->ItemID;
					$shop_id = $listing['shop_id'];
					$site = $listing['site'];
					$get_result = Online_Ebay_Listing::getItem($shop_id, $item_id, $site);
					if ($get_result['ack'] == SUCCESS)
					{
						$listing_relist = $get_result['listing'];
						$listing_relist['item_id'] = $item_id;
						$listing_relist['shop_id'] = $shop_id;
						$listing_relist['site'] = $site;
						$listing_relist['currency_id'] = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'currency_id');
						Online_Ebay_Listing::update($listing_relist);
						return array('ack' => SUCCESS, 'message' => '');
					}
					else
					{
						return array('ack' => FAILURE, 'message' => $get_result['message']);
					}
				}
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function end($listing_id, $reason)
	{
		$listing = Online_Ebay_Listing::find('id=?', $listing_id)->asArray()->getOne();
		if ($listing['item_id'])
		{
			$token = Shop_API_Ebay::find('shop_id=?', $listing['shop_id'])->asArray()->getOne();
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $listing['site'], 'site_id');
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:EndItem'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<EndItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<EndingReason>' . $reason . '</EndingReason>';
			$xml .= 	'<ItemID>' . $listing['item_id'] . '</ItemID>';
			$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
			$xml .= '</EndItemRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'EndItem');
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if ($response->Ack == 'Success')
				{
					QDB::getConn()->execute('update online_ebay_listing set sell_status=' . Q::ini('custom_flag/online_ebay_listing_sell_status/ended/value') . ' where id=' . $listing['id']);
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					$error = is_array($response->Errors) ? $response->Errors : array($response->Errors);
					$error_str = '';
					foreach ($error as $e)
					{
						$error_str .= htmlspecialchars($e->ShortMessage) . ',';
					}
					return array('ack' => FAILURE, 'message' => $error_str);
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '从未上架');
		}
	}
	
	static function assembleItemXMLByListing($listing)
	{
		$xml = '<PrimaryCategory>';
		$xml .= 	'<CategoryID>' . $listing['primary_category'] . '</CategoryID>';
		$xml .= '</PrimaryCategory>';
		if ($listing['second_category'])
		{
			$xml .= '<SecondaryCategory>';
			$xml .= 	'<CategoryID>' . $listing['second_category'] . '</CategoryID>';
			$xml .= '</SecondaryCategory>';
		}
		if (( ! empty($listing['store_category'])) || ( ! empty($listing['store_category2'])))
		{
			$xml .= '<Storefront>';
			if ( ! empty($listing['store_category']))
			{
				$xml .= '<StoreCategoryID>' . $listing['store_category'] . '</StoreCategoryID>';
			}
			if ( ! empty($listing['store_category2']))
			{
				$xml .= '<StoreCategory2ID>' . $listing['store_category2'] . '</StoreCategory2ID>';
			}
			$xml .= '</Storefront>';
		}
		$xml .= '<Title>' . htmlspecialchars($listing['title']) . '</Title>';
		if ($listing['condition_id'])
		{
			$xml .= '<ConditionID>' . $listing['condition_id'] . '</ConditionID>';
		}
		if ($listing['condition_description'])
		{
			$xml .= '<ConditionDescription>' . htmlspecialchars($listing['condition_description']) . '</ConditionDescription>';
		}
		$xml .= '<ListingType>' . $listing['listing_type'] . '</ListingType>';
		$xml .= '<ListingDuration>' . $listing['listing_duration'] . '</ListingDuration>';
		if ($listing['item_specifics'])
		{
			$xml .= '<ItemSpecifics>';
			foreach ($listing['item_specifics'] as $is)
			{
				$xml .= '<NameValueList>';
				$xml .= 	'<Name>' . htmlspecialchars($is['name']) . '</Name>';
				$xml .= 	'<Value>' . htmlspecialchars($is['value']) . '</Value>';
				$xml .= '</NameValueList>';
			}
			$xml .= '</ItemSpecifics>';
		}
		if ($listing['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
		{
			$xml .= '<Variations>';
			if ($listing['picture']['variation_picture'])
			{
				$xml .= '<Pictures>';
				$xml .= 	'<VariationSpecificName>' . htmlspecialchars($listing['picture']['variation_picture'][0]['specific_name']) . '</VariationSpecificName>';
				foreach ($listing['picture']['variation_picture'] as $vp)
				{
					$xml .= '<VariationSpecificPictureSet>';
					$xml .= 	'<PictureURL>' . $vp['picture_url'] . '</PictureURL>';
					$xml .= 	'<VariationSpecificValue>' . htmlspecialchars($vp['specific_value']) . '</VariationSpecificValue>';
					$xml .= '</VariationSpecificPictureSet>';
				}
				$xml .= '</Pictures>';
			}
			$specifics_set = array();
			foreach ($listing['item'] as $li)
			{
				$xml .= '<Variation>';
				$xml .= 	'<Quantity>' . $li['quantity'] . '</Quantity>';
				$xml .= 	'<SKU>' . $li['sku'] . '</SKU>';
				$xml .= 	'<StartPrice>' . $li['start_price'] . '</StartPrice>';
				$xml .= 	'<VariationSpecifics>';
				foreach ($li['specifics'] as $lis)
				{
					$xml .= 	'<NameValueList>';
					$xml .= 		'<Name>' . htmlspecialchars($lis['name']) . '</Name>';
					$xml .= 		'<Value>' . htmlspecialchars($lis['value']) . '</Value>';
					$xml .= 	'</NameValueList>';
					if ( ! isset($specifics_set[$lis['name']]) || ! in_array($lis['value'], $specifics_set[$lis['name']]))
					{
						$specifics_set[$lis['name']][] = $lis['value'];
					}
				}
				$xml .= 	'</VariationSpecifics>';
				$xml .= '</Variation>';
			}
			if ($specifics_set)
			{
				$xml .= '<VariationSpecificsSet>';
				foreach ($specifics_set as $s_name => $ss)
				{
					$xml .= '<NameValueList>';
					$xml .= 	'<Name>' . htmlspecialchars($s_name) . '</Name>';
					foreach ($ss as $s)
					{
						$xml .= '<Value>' . htmlspecialchars($s) . '</Value>';
					}
					$xml .= '</NameValueList>';
				}
				$xml .= '</VariationSpecificsSet>';
			}
			$xml .= '</Variations>';
		}
		else
		{
			$xml .= '<SKU>' . $listing['item'][0]['sku'] . '</SKU>'; 
			$xml .= '<Quantity>' . $listing['item'][0]['quantity'] . '</Quantity>';
			$xml .= '<StartPrice>' . $listing['item'][0]['start_price'] . '</StartPrice>';
			$xml .= ((isset($listing['item'][0]['buy_it_now_price']) && $listing['item'][0]['buy_it_now_price'] > 0) ? ('<BuyItNowPrice>' . $listing['item'][0]['buy_it_now_price'] . '</BuyItNowPrice>') : '');
		}
		$xml .= '<PictureDetails>';
		foreach ($listing['picture']['listing_picture'] as $k => $lp)
		{
			if ($k == 0)
			{
				$xml .= '<GalleryURL>' . $lp['picture_url'] . '</GalleryURL>';
			}
			$xml .= '<PictureURL>' . $lp['picture_url'] . '</PictureURL>';
		}
		$xml .= '</PictureDetails>';
		$xml .= '<Description>' . htmlspecialchars($listing['description']) . '</Description>';
		$xml .= '<HitCounter>' . $listing['counter'] . '</HitCounter>';
		$xml .= '<PaymentMethods>' . $listing['payment_method'] . '</PaymentMethods>';
		$xml .= '<PayPalEmailAddress>' . $listing['payment_address'] . '</PayPalEmailAddress>';
		$xml .= '<AutoPay>' . Helper_BSS_Normal::getIniOne('online_ebay_listing_auto_pay', 'value', $listing['auto_pay'], 'boolean_value') . '</AutoPay>';
		$xml .= '<DispatchTimeMax>' . $listing['dispatch_time'] . '</DispatchTimeMax>';
		$xml .= '<GetItFast>' . Helper_BSS_Normal::getIniOne('online_ebay_listing_get_it_fast', 'value', $listing['get_it_fast'], 'boolean_value') . '</GetItFast>';
		$xml .= '<ShippingDetails>';
		$domestic_sort = 1;
		foreach ($listing['shipping_service']['domestic_shipping'] as $ds)
		{
			$xml .= '<ShippingServiceOptions>';
			$xml .= 	'<ShippingService>' . $ds['service'] . '</ShippingService>';
			$xml .= 	'<ShippingServicePriority>' . $domestic_sort++ . '</ShippingServicePriority>';
			if ($ds['free'] == Q::ini('custom_flag/online_ebay_listing_shipping_free/free/value'))
			{
				$xml .= '<FreeShipping>true</FreeShipping>';
			}
			else
			{
				$xml .= '<ShippingServiceCost>' . $ds['cost'] . '</ShippingServiceCost>';
				$xml .= '<ShippingServiceAdditionalCost>' . $ds['additional_cost'] . '</ShippingServiceAdditionalCost>';
			}
			$xml .= '</ShippingServiceOptions>';
		}
		$international_sort = 1;
		foreach ($listing['shipping_service']['international_shipping'] as $is)
		{
			$xml .= '<InternationalShippingServiceOption>';
			$xml .= 	'<ShippingService>' . $is['service'] . '</ShippingService>';
			$xml .= 	'<ShippingServiceCost>' . $is['cost'] . '</ShippingServiceCost>';
			$xml .= 	'<ShippingServicePriority>' . $international_sort++ . '</ShippingServicePriority>';
			$xml .= 	'<ShippingServiceAdditionalCost>' . $is['additional_cost'] . '</ShippingServiceAdditionalCost>';
			$shipping_location = explode(',', $is['shipping_location']);
			foreach ($shipping_location as $sl)
			{
				$xml .= '<ShipToLocation>' . $sl . '</ShipToLocation>';
			}
			$xml .= '</InternationalShippingServiceOption>';
		}
		$xml .= '</ShippingDetails>';
		$xml .= '<Country>' . $listing['country'] . '</Country>';
		$xml .= '<PostalCode>' . $listing['postal_code'] . '</PostalCode>';
		$xml .= '<Location>' . $listing['location'] . '</Location>';
		$xml .= '<ReturnPolicy>';
		$xml .= 	'<ReturnsAcceptedOption>' . $listing['return_policy'] . '</ReturnsAcceptedOption>';
		if ($listing['return_policy'] == 'ReturnsAccepted')
		{
			if ($listing['return_option_restocking'])
			{
				$xml .= '<RestockingFeeValueOption>' . $listing['return_option_restocking'] . '</RestockingFeeValueOption>';
			}
			if ($listing['return_option_within'])
			{
				$xml .= '<ReturnsWithinOption>' . $listing['return_option_within'] . '</ReturnsWithinOption>';
			}
			if ($listing['return_option_refund'])
			{
				$xml .= '<RefundOption>' . $listing['return_option_refund'] . '</RefundOption>';
			}
			if ($listing['return_option_paid_by'])
			{
				$xml .= '<ShippingCostPaidByOption>' . $listing['return_option_paid_by'] . '</ShippingCostPaidByOption>';
			}
			if ($listing['return_option_description'])
			{
				$xml .= '<Description>' . htmlspecialchars($listing['return_option_description']) . '</Description>';
			}
		}
		$xml .= '</ReturnPolicy>';
		return $xml;
	}
	
	static function getListingById($listing_id)
	{
		$listing = Online_Ebay_Listing::find('id=?', $listing_id)->asArray()->getOne();
		if ($listing)
		{
			$item = Online_Ebay_Listing_Item::find('online_ebay_listing_id=?', $listing['id'])->asArray()->getAll();
			if ($listing['variation'] == Q::ini('custom_flag/online_ebay_listing_variation/variation/value'))
			{
				foreach ($item as $k => $i)
				{
					$item[$k]['specifics'] = Online_Ebay_Listing_Specifics::find('type=? and relate_table_id=?', Q::ini('custom_flag/online_ebay_listing_specifics_type/variation'), $i['id'])->asArray()->getAll();
				}
			}
			$listing['item'] = $item;
			$item_specifics = Online_Ebay_Listing_Specifics::find('type=? and relate_table_id=?', Q::ini('custom_flag/online_ebay_listing_specifics_type/listing'), $listing['id'])->asArray()->getAll();
			$listing['item_specifics'] = $item_specifics;
			$picture = Online_Ebay_Listing_Picture::getListingPicture($listing['id']);
			$listing['picture']['listing_picture'] = $picture['listing'];
			$listing['picture']['variation_picture'] = $picture['variation'];
			$shipping = Online_Ebay_Listing_Shipping::getListingShipping($listing['id']);
			$listing['shipping_service']['domestic_shipping'] = $shipping['domestic'];
			$listing['shipping_service']['international_shipping'] = $shipping['international'];
			Online_Ebay_Listing_Extend::getListingExtend($listing);
			return array('ack' => SUCCESS, 'message' => '', 'listing' => $listing);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '该Listing不存在');
		}
	}
	
	static function getSellerList($shop_id, $from_time, $to_time)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $shop_id)->asArray()->getOne();
		if ($token)
		{
			$shop = Shop::find('id=?', $shop_id)->asArray()->getOne();
			$ps = 200;
			$cp = 0;
			$total_entries = 1;
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:0',
				'X-EBAY-API-CALL-NAME:GetSellerList'
			);
			while ($ps * $cp < $total_entries)
			{
				$cp++;
				$xml = '<?xml version="1.0" encoding="utf-8"?>';
				$xml .= '<GetSellerListRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
				$xml .= 	'<RequesterCredentials>';
				$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
				$xml .= 	'</RequesterCredentials>';
				$xml .= 	'<IncludeWatchCount>true</IncludeWatchCount>';
				$xml .= 	'<IncludeVariations>true</IncludeVariations>';
				$xml .= 	'<EndTimeFrom>' . $from_time . '</EndTimeFrom>';
				$xml .= 	'<EndTimeTo>' . $to_time . '</EndTimeTo>';
				$xml .= 	'<DetailLevel>ItemReturnDescription</DetailLevel>';
				$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
				$xml .= 	'<Pagination>';
				$xml .= 		'<EntriesPerPage>' . $ps . '</EntriesPerPage>';
				$xml .= 		'<PageNumber>' . $cp . '</PageNumber>';
				$xml .= 	'</Pagination>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Site</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Currency</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.ItemID</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.PrimaryCategory.CategoryID</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Title</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.ListingType</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.ListingDuration</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.HitCounter</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.HitCount</OutputSelector>';
				$xml .=		'<OutputSelector>ItemArray.Item.SellingStatus.ListingStatus</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.ListingDetails.StartTime</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.ListingDetails.EndTime</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.ListingDetails.ViewItemURL</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.WatchCount</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Location</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.SKU</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Quantity</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.StartPrice</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.BuyItNowPrice</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.SellingStatus.QuantitySold</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Variations.Variation.SKU</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Variations.Variation.Quantity</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Variations.Variation.StartPrice</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Variations.Variation.VariationSpecifics</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Variations.Variation.VariationSpecifics.NameValueList.Name</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Variations.Variation.VariationSpecifics.NameValueList.Value</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.Variations.Variation.SellingStatus.QuantitySold</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.PictureDetails.GalleryURL</OutputSelector>';
				$xml .= 	'<OutputSelector>ItemArray.Item.PictureDetails.PictureURL</OutputSelector>';
				$xml .= 	'<OutputSelector>PaginationResult</OutputSelector>';
				$xml .= '</GetSellerListRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GetSellerList');
				$result['ack'] = SUCCESS;
				if ($result['ack'] == SUCCESS)
				{
					$response = json_decode(json_encode(simplexml_load_string($result['data'])));
					if ($response->Ack == 'Success')
					{
						$total_entries = $response->PaginationResult->TotalNumberOfEntries;
						if (isset($response->ItemArray->Item))
						{
							if (is_array($response->ItemArray->Item))
							{
								$item = $response->ItemArray->Item;
							}
							else
							{
								$item = array($response->ItemArray->Item);
							}
							$listing = Helper_BSS_Array::EbayItemsArray($item, $shop);
							Online_Ebay_Listing::import($listing);
						}
					}
				}
			}
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function import($listings)
	{
		$currency_in_db = Currency::find()->asArray()->getAll();
		$currency = array();
		foreach ($currency_in_db as $c)
		{
			$currency[$c['code']] = $c['id'];
		}
		foreach ($listings as $l)
		{
			$listing = Online_Ebay_Listing::find('shop_id=? and item_id=? and site=?', $l['shop_id'], $l['item_id'], $l['site'])->getOne();
			if ( ! $listing['id'])
			{
				$listing = new Online_Ebay_Listing();
				$listing->site = $l['site'];
				$listing->shop_id = $l['shop_id'];
				$listing->item_id = $l['item_id'];
				$listing->create_time = date('Y-m-d H:i:s');
			}
			$listing->currency_id = $currency[$l['currency_code']];
			$listing->primary_category = $l['primary_category'];
			$listing->listing_type = $l['listing_type'];
			$listing->listing_duration = $l['listing_duration'];
			$listing->variation = $l['variation'];
			$listing->counter = $l['counter'];
			$listing->hit_count = $l['hit_count'];
			$listing->payment_method = $l['payment_method'];
			$listing->payment_address = $l['payment_address'];
			$listing->sell_status = $l['sell_status'];
			$listing->start_time = $l['start_time'];
			$listing->end_time = $l['end_time'];
			$listing->watch_count = $l['watch_count'];
			$listing->quantity = $l['quantity'];
			$listing->sold_quantity = $l['sold_quantity'];
			$listing->start_price = $l['start_price'];
			$listing->location = $l['location'];
			$listing->lib_flag = Q::ini('custom_flag/ebay_listing_lib_flag/unflag/value');
			$listing->save();
			$listing_id = $listing['id'];
			$extend = array();
			$extend['title'] = $l['title'];
			$extend['view_url'] = $l['view_url'];
			Online_Ebay_Listing_Extend::update($extend, $listing_id);
			Online_Ebay_Listing_Item::update($l['item'], $listing_id);
			Online_Ebay_Listing_Picture::update($l['picture']['listing_picture'], $listing_id, Q::ini('custom_flag/online_ebay_listing_picture_type/listing/value'));
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function keepQuantityExecute()
	{
		$variation = Q::ini('custom_flag/online_ebay_listing_variation/variation/value');
		$item = Online_Ebay_Listing_Item::find('online_ebay_listing_item.keep_quantity_flag=? and online_ebay_listing.listing_type=? and online_ebay_listing.listing_duration=? and online_ebay_listing.sell_status=?', Q::ini('custom_flag/online_ebay_listing_item_keep_quantity_flag/keep/value'), 'FixedPriceItem', 'GTC', Q::ini('custom_flag/online_ebay_listing_sell_status/active/value'))
			->joinLeft('online_ebay_listing', 'shop_id, item_id, variation, site', 'online_ebay_listing.id=online_ebay_listing_item.online_ebay_listing_id')
			->asArray()->getAll();
		$listing = array();
		foreach ($item as $i)
		{
			if ( ! isset($listing[$i['item_id']]))
			{
				$listing[$i['item_id']] = array('id' => $i['online_ebay_listing_id'], 'item_id' => $i['item_id'], 'shop_id' => $i['shop_id'], 'site' => $i['site'], 'variation' => $i['variation'], 'item' => array());
			}
			$listing[$i['item_id']]['item'][] = array('sku' => $i['sku'], 'quantity' => $i['keep_quantity']);
		}
		$message = array();
		foreach ($listing as $l)
		{
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $l['site'], 'site_id');
			$token = Shop_API_Ebay::find('shop_id=?', $l['shop_id'])->asArray()->getOne();
			if ($l['variation'] == $variation)
			{
				$header = array(
					'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
					'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
					'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
					'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
					'X-EBAY-API-SITEID:' . $site_id,
					'X-EBAY-API-CALL-NAME:ReviseFixedPriceItem'
				);
				$xml = '<?xml version="1.0" encoding="utf-8"?>';
				$xml .= '<ReviseFixedPriceItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
				$xml .= 	'<RequesterCredentials>';
				$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
				$xml .= 	'</RequesterCredentials>';
				$xml .= 	'<MessageID>' . $l['item_id'] . '</MessageID>';
				$xml .= 	'<WarningLevel>High</WarningLevel>';
				$xml .= 	'<Item>';
				$xml .= 		'<ItemID>' . $l['item_id'] . '</ItemID>';
				$xml .= 		'<OutOfStockControl>true</OutOfStockControl>';
				$xml .= 		'<Variations>';
				foreach ($l['item'] as $li)
				{
					$xml .= 		'<Variation>';
					$xml .=				'<SKU>' . $li['sku'] . '</SKU>';
					$xml .= 			'<Quantity>' . $li['quantity'] . '</Quantity>';
					$xml .= 		'</Variation>';
				}
				$xml .= 		'</Variations>';
				$xml .= 	'</Item>';
				$xml .= '</ReviseFixedPriceItemRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'ReviseFixedPriceItem');
			}
			else
			{
				$first_item = current($l['item']);
				$header = array(
					'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
					'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
					'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
					'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
					'X-EBAY-API-SITEID:' . $site_id,
					'X-EBAY-API-CALL-NAME:ReviseItem'
				);
				$xml = '<?xml version="1.0" encoding="utf-8"?>';
				$xml .= '<ReviseItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
				$xml .= 	'<RequesterCredentials>';
				$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
				$xml .= 	'</RequesterCredentials>';
				$xml .= 	'<WarningLevel>High</WarningLevel>';
				$xml .= 	'<MessageID>' . $l['item_id'] . '</MessageID>';
				$xml .= 	'<Item>';
				$xml .= 		'<ItemID>' . $l['item_id'] . '</ItemID>';
				$xml .= 		'<OutOfStockControl>true</OutOfStockControl>';
				$xml .= 		'<SKU>' . $first_item['sku'] . '</SKU>';
				$xml .= 		'<Quantity>' . $first_item['quantity'] . '</Quantity>';
				$xml .= 	'</Item>';
				$xml .= '</ReviseItemRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'ReviseItem');
			}
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if ($response->Ack == 'Success' || $response->Ack == 'Warning')
				{
					foreach ($l['item'] as $li)
					{
						QDB::getConn()->execute('update online_ebay_listing_item set quantity=' . $li['quantity'] . ' where online_ebay_listing_id=' . $l['id'] . ' and sku=\'' . $li['sku'] . '\'');
					}
					Online_Ebay_Listing::updateListingPriceAndQuantity($l['id']);
				}
				else
				{
					$errors = array();
					if (isset($response->Errors))
					{
						if (is_array($response->Errors))
						{
							foreach ($response->Errors as $e)
							{
								$errors[] = htmlspecialchars($e->LongMessage);
							}
						}
						else
						{
							$errors[] = htmlspecialchars($response->Errors->LongMessage);
						}
					}
					$message[] = $l['item_id'] . ':' . implode(', ', $errors);
				}
			}
			else
			{
				$message[] = $l['item_id'] . ':' . $result['message'];
			}
		}
		return array('ack' => SUCCESS, 'message' => implode(';', $message));
	}
	
	static function updateListing($listing_id, $force = false)
	{
		$listing = Online_Ebay_Listing::find('id=?', $listing_id)->asArray()->getOne();
		if ($listing['id'] && $listing['item_id'])
		{
			if ($force || ((CURRENT_TIMESTAMP - strtotime($listing['update_time']) > 86400 * 5)))
			{
				$get_result = Online_Ebay_Listing::getItem($listing['shop_id'], $listing['item_id'], $listing['site']);
				if ($get_result['ack'] == SUCCESS)
				{
					$new_listing = $get_result['listing'];
					$new_listing['id'] = $listing_id;
					Online_Ebay_Listing::update($new_listing);
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $get_result['message']);
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '不需要更新');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'listing不存在');
		}
	}
	
	static function getItem($shop_id, $item_id, $site)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $shop_id)->asArray()->getOne();
		if ($token)
		{
			$site_id = Helper_BSS_Normal::getIniOne('online_ebay_listing_site', 'value', $site, 'site_id');
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:' . $site_id,
				'X-EBAY-API-CALL-NAME:GetItem'
			);
			$xml = '<?xml version="1.0" encoding="utf-8"?>';
			$xml .= '<GetItemRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .= 	'<RequesterCredentials>';
			$xml .= 		'<eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .= 	'</RequesterCredentials>';
			$xml .= 	'<ItemID>' . $item_id . '</ItemID>';
			$xml .= 	'<IncludeWatchCount>true</IncludeWatchCount>';
			$xml .= 	'<IncludeItemSpecifics>true</IncludeItemSpecifics>';
			$xml .= 	'<OutputSelector>Item.Site</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Currency</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ItemID</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.PrimaryCategory.CategoryID</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.SecondaryCategory.CategoryID</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Storefront.StoreCategoryID</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Storefront.StoreCategory2ID</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Title</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ConditionID</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ConditionDisplayName</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ConditionDescription</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ListingType</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ListingDuration</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.HitCounter</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.HitCount</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.DispatchTimeMax</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.AutoPay</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.GetItFast</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Country</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.PostalCode</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Location</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ReturnPolicy.ReturnsAcceptedOption</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ReturnPolicy.RestockingFeeValueOption</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ReturnPolicy.ReturnsWithinOption</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ReturnPolicy.RefundOption</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ReturnPolicy.ShippingCostPaidByOption</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ReturnPolicy.Description</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.SellingStatus.ListingStatus</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ListingDetails.StartTime</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ListingDetails.EndTime</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ListingDetails.ViewItemURL</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.WatchCount</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.SKU</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Quantity</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Description</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.StartPrice</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.BuyItNowPrice</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.SellingStatus.QuantitySold</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Variations.Variation.SKU</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Variations.Variation.Quantity</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Variations.Variation.StartPrice</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Variations.Variation.VariationSpecifics</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Variations.Variation.VariationSpecifics.NameValueList.Name</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Variations.Variation.VariationSpecifics.NameValueList.Value</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Variations.Variation.SellingStatus.QuantitySold</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Variations.Pictures.VariationSpecificName</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Variations.Pictures.VariationSpecificPictureSet.PictureURL</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.Variations.Pictures.VariationSpecificPictureSet.VariationSpecificValue</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ShippingDetails.ShippingServiceOptions.ShippingService</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ShippingDetails.ShippingServiceOptions.ShippingServiceCost</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ShippingDetails.ShippingServiceOptions.ShippingServicePriority</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ShippingDetails.ShippingServiceOptions.ShippingServiceAdditionalCost</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ShippingDetails.ShippingServiceOptions.FreeShipping</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ShippingDetails.InternationalShippingServiceOption.ShippingService</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ShippingDetails.InternationalShippingServiceOption.ShippingServiceCost</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ShippingDetails.InternationalShippingServiceOption.ShippingServicePriority</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ShippingDetails.InternationalShippingServiceOption.ShippingServiceAdditionalCost</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ShippingDetails.InternationalShippingServiceOption.ShipToLocation</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.PictureDetails.GalleryURL</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.PictureDetails.PictureURL</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ItemSpecifics.NameValueList.Name</OutputSelector>';
			$xml .= 	'<OutputSelector>Item.ItemSpecifics.NameValueList.Value</OutputSelector>';
			$xml .= 	'<DetailLevel>ReturnAll</DetailLevel>';
			$xml .= 	'<WarningLevel>High</WarningLevel>';
			$xml .= 	'<ErrorLanguage>en_US</ErrorLanguage>';
			$xml .= '</GetItemRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GetItem');
			if ($result['ack'] == SUCCESS)
			{
				$response = json_decode(json_encode(simplexml_load_string($result['data'])));
				if ($response->Ack == 'Success')
				{
					$listing = Helper_BSS_Array::EbayItemDetailArray($response->Item);
					return array('ack' => SUCCESS, 'message' => '', 'listing' => $listing);
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '店铺缺少授权信息');
		}
	}
	
	static function updateListingPriceAndQuantity($listing_id)
	{
		$item = Online_Ebay_Listing_Item::find('online_ebay_listing_id=?', $listing_id)->asArray()->getAll();
		$start_price = $quantity = 0;
		foreach ($item as $i)
		{
			$start_price = ($start_price > 0) ? min($start_price, $i['start_price']) : $i['start_price'];
			$quantity += $i['quantity'];
		}
		QDB::getConn()->execute('update online_ebay_listing set start_price=' . $start_price . ', quantity=' . $quantity . ' where id=' . $listing_id);
	}
	
	static function GetProductTraceData($condition, $cp='', $ps='')
	{
		$order_by = '';
		if (isset($condition['sort_by']) && isset($condition['sort_order']))
		{
			$order_by = $condition['sort_by'] . ' ' . $condition['sort_order'];
		}
		$condition['warehouse_id'] = Warehouse::getDefaultWarehouseId();
		$search_result = Product_Warehouse::search($condition, $cp, $ps, $order_by);
		foreach ($search_result['data'] as &$r)
		{
			$shop = Online_Ebay_Listing_item::find('product_basic_id=?', $r['product_basic_id'])
				->joinLeft('online_ebay_listing', 'online_ebay_listing.shop_id', 'online_ebay_listing.end_time >\''. date("Y-m-d H:i:s") . '\' and online_ebay_listing.sell_status=' . Q::ini('custom_flag/online_ebay_listing_sell_status/active/value') . ' and online_ebay_listing.lib_flag = ' . Q::ini('custom_flag/ebay_listing_lib_flag/unflag/value') . ' and online_ebay_listing.listing_type like "' . Q::ini('custom_flag/online_ebay_listing_type/fixedpriceitem/value') . '" and online_ebay_listing.id=online_ebay_listing_item.online_ebay_listing_id')
				->asArray()->getAll();
			$array = "";
			foreach ($shop as $s)
			{
				if ($s['shop_id'])
				{
					$array[] = $s['shop_id']; 
				}
			}
			if (!empty($array))
			{
				$r['shop_count'] = count(array_unique($array));
			}
			else
			{
				$r['shop_count'] = 0;
			}
		}
		unset($r);
		return $search_result;
	}
	
	static function search($condition, $cp, $ps, $sort_order = '')
	{
		$columns = array('shop.name as shop_name', 'currency.code as currency_code', 'user.name as create_user_name', 'online_ebay_listing.*');
		$where = Online_Ebay_Listing::buildSearchWhere($condition);
		$select = Online_Ebay_Listing::find($where)
			->joinLeft('shop', '', 'shop.id=online_ebay_listing.shop_id')
			->joinLeft('currency', '', 'currency.id=online_ebay_listing.currency_id')
			->joinLeft('user', '', 'user.id=online_ebay_listing.create_user_id')
			->order($sort_order);
		if ($cp == 0 && $ps == 0)
		{
			$pagination = array();
		}
		else
		{
			$select->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$listing = $select->setColumns($columns)->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $listing,
			'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if ( ! empty($condition['shop_ids']))
		{
			$where .= ' and online_ebay_listing.shop_id in (' . implode(',', $condition['shop_ids']) . ')';
		}
		if ( ! empty($condition['site']))
		{
			$where .= ' and online_ebay_listing.site in (\'' . implode('\',\'', $condition['site']) . '\')';
		}
		if ( ! empty($condition['begin_start_time']))
		{
			$where .= ' and online_ebay_listing.start_time>=\'' . $condition['begin_start_time'] . '\'';
		}
		if ( ! empty($condition['end_start_time']))
		{
			$where .= ' and online_ebay_listing.start_time<=\'' . $condition['end_start_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['begin_end_time']))
		{
			$where .= ' and online_ebay_listing.end_time>=\'' . $condition['begin_end_time'] . '\'';
		}
		if ( ! empty($condition['end_end_time']))
		{
			$where .= ' and online_ebay_listing.end_time<=\'' . $condition['end_end_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['begin_create_time']))
		{
			$where .= ' and online_ebay_listing.create_time>=\'' . $condition['begin_create_time'] . '\'';
		}
		if ( ! empty($condition['end_create_time']))
		{
			$where .= ' and online_ebay_listing.create_time<=\'' . $condition['end_create_time'] . ' 23:59:59\'';
		}
		if ( ! empty($condition['create_user_name']))
		{
			$where .= ' and user.name=\'' . $condition['create_user_name'] . '\'';
		}
		if (isset($condition['sold_quantity']) && $condition['sold_quantity'] !== '' && !empty($condition['sold_quantity_operator']))
		{
			$where .= ' and online_ebay_listing.sold_quantity' . $condition['sold_quantity_operator'] . $condition['sold_quantity'];
		}
		if ( ! empty($condition['item_id']))
		{
			$where .= ' and online_ebay_listing.item_id=\'' . $condition['item_id'] . '\'';
		}
		if ( ! empty($condition['status']))
		{
			$where .= ' and online_ebay_listing.status in (' . implode(',', $condition['status']) . ')';
		}
		if ( ! empty($condition['sell_status']))
		{
			$where .= ' and online_ebay_listing.sell_status in (' . implode(',', $condition['sell_status']) . ')';
		}
		if ( ! empty($condition['listing_duration']))
		{
			$where .= ' and online_ebay_listing.listing_duration in (\'' . implode('\',\'', $condition['listing_duration']) . '\')';
		}
		if ( ! empty($condition['listing_type']))
		{
			$where .= ' and online_ebay_listing.listing_type in (\'' . implode('\',\'', $condition['listing_type']) . '\')';
		}
		if ( ! empty($condition['edit_flag']))
		{
			$where .= ' and online_ebay_listing.edit_flag in (' . implode(',', $condition['edit_flag']) . ')';
		}
		if ( ! empty($condition['variation']))
		{
			$where .= ' and online_ebay_listing.variation in (' . implode(',', $condition['variation']) . ')';
		}
		if ( ! empty($condition['sku']))
		{
			$temp = explode(',', $condition['sku']);
			$sku = array();
			foreach ($temp as $t)
			{
				$sku[] = trim($t);
			}
			$item_where = 'online_ebay_listing_item.sku in (\'' . implode('\',\'', $sku) . '\')';
			$listing_id = Online_Ebay_Listing_Item::find($item_where)
				->setColumns('online_ebay_listing_id as id')->asArray()->getAll();
			$item_sku = array();
			foreach ($listing_id as $l)
			{
				$item_sku[] = $l['id'];
			}
			$where .= ' and online_ebay_listing.id in (\'' . implode('\',\'', $item_sku) . '\')';
		}
		if ( ! empty($condition['schedule_flag']))
		{
			$where .= ' and online_ebay_listing.schedule_flag in (' . implode(',', $condition['schedule_flag']) . ')';
		}
		if ( ! empty($condition['schedule_repeat']))
		{
			$where .= ' and online_ebay_listing.schedule_repeat in (' . implode(',', $condition['schedule_repeat']) . ')';
		}
		if (isset($condition['schedule_repeat_step']) && $condition['schedule_repeat_step'] !== '' && !empty($condition['schedule_repeat_step_operator']))
		{
			$where .= ' and online_ebay_listing.schedule_repeat_step' . $condition['schedule_repeat_step_operator'] . $condition['schedule_repeat_step'];
		}
		if (isset($condition['lib_flag']))
		{
			$where .= ' and online_ebay_listing.lib_flag=\'' . $condition['lib_flag'] . '\'';
		}
		if ( ! empty($condition['push_flag']))
		{
			$where .= ' and online_ebay_listing.push_flag in (' . implode(',', $condition['push_flag']) . ')';
		}
		if ( ! empty($condition['folder_ids']))
		{
			$where .= ' and online_ebay_listing.online_ebay_listing_folder_id in (' . implode(',', $condition['folder_ids']) . ')';
		}
		return $where;
	}
}